package com.haliyoo.adhs.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.haliyoo.adhs.action.UserAction;
import com.haliyoo.adhs.dao.AdRepostDao;
import com.haliyoo.adhs.exception.DaoLevelException;
import com.haliyoo.adhs.model.AdRepost;
import com.haliyoo.adhs.service.impl.UserServiceImpl;

public class AdRepostDaoImpl implements AdRepostDao {
	
	private static final Logger	logger	= Logger.getLogger(AdRepostDaoImpl.class);
	
	private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
    @SuppressWarnings("unchecked")
    public List<AdRepost> findAll() throws DaoLevelException {
    	List<AdRepost> adRepostList = null;
    	try{
	        Query query = getEntityManager().createQuery("select p FROM AdRepost p");
	        adRepostList = query.getResultList();
	    }catch(Exception e){
	    	throw new DaoLevelException("error -- List<AdRepost> findAll()",e);
	    }
	    return adRepostList;
    }

    public void save(AdRepost adRepost) throws DaoLevelException {
        if (adRepost.getId() == null) {
        	try{
        		logger.debug("adRepost.getId() ,adRepost.getId() :" +adRepost.getId());
        		adRepost.setRepostTime(new Date());
	            em.persist(adRepost);// new
	        }catch(Exception e){
		    	throw new DaoLevelException("error -- save(AdRepost adRepost) -- em.persist(user)",e);
		    }
        } else {
        	try{
	            em.merge(adRepost); // update
	        }catch(Exception e){
		    	throw new DaoLevelException("error -- save(AdRepost adRepost) -- em.merge(user)",e);
		    }
        }
    }

    public void remove(AdRepost adRepost) throws DaoLevelException {
        if (adRepost != null) {
        	try{
	            em.remove(em.merge(adRepost));
	        }catch(Exception e){
		    	throw new DaoLevelException("error -- remove(Integer id)",e);
		    }
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    public AdRepost find(Integer id) throws DaoLevelException {
    	AdRepost adRepost = null;
    	try{
	    	adRepost = em.find(AdRepost.class, id);
	    }catch(Exception e){
	    	throw new DaoLevelException("error -- remove(Integer id)",e);
	    }
	    return adRepost;
    }
}